import {ModalForm, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton} from '@ant-design/pro-components';
import {Form, Upload, message, Button} from 'antd';
import React, {useState} from 'react';
import {UploadOutlined} from '@ant-design/icons';
import {API} from "@/services/typings";
import {listSettingGroupAPI} from "@/pages/system/setting/service";

interface SettingFormProps {
  trigger?: React.ReactNode;
  initialValues?: API.ISetting;
  onFinish: (values: API.ISetting) => Promise<boolean>;
  title?: string;
  onOpenChange?: (open: boolean) => void;
}

const SettingForm: React.FC<SettingFormProps> = ({
                                                   trigger,
                                                   initialValues,
                                                   onFinish,
                                                   title,
                                                   onOpenChange
                                                 }) => {
  const [form] = Form.useForm<API.ISetting>();
  const [fileList, setFileList] = useState<any[]>([]);

  const handleUploadChange = (info: any) => {
    let newFileList = [...info.fileList];
    newFileList = newFileList.slice(-1); // 只保留一个文件
    setFileList(newFileList);

    if (info.file.status === 'done') {
      message.success(`${info.file.name} 文件上传成功`);
      form.setFieldsValue({settingValue: info.file.response.data.id});
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 文件上传失败`);
    }
  };

  return (
    <ModalForm<API.ISetting>
      form={form}
      title={title || (initialValues ? '编辑系统设置' : '新增系统设置')}
      trigger={trigger as any}
      initialValues={initialValues}
      onFinish={async (values) => {
        // 处理文件上传情况
        return onFinish(values);
      }}
      onOpenChange={(open) => {
        if (!open) {
          form.resetFields();
          setFileList([]);
        }
        onOpenChange?.(open);
      }}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
        width: 480,
      }}
    >
      <ProFormText
        name="name"
        label="设置名称"
        rules={[{required: true, message: '请输入设置名称'}]}
        placeholder="请输入设置名称"
      />

      <ProFormText
        name="settingKey"
        label="配置键"
        rules={[{required: true, message: '请输入配置键'}]}
        placeholder="如：system.logo"
      />

      <ProFormSelect
        name="settingType"
        label="配置类型"
        rules={[{required: true, message: '请选择配置类型'}]}
        options={[
          {label: '字符串', value: 'string'},
          {label: '数值', value: 'number'},
          {label: '布尔值', value: 'boolean'},
          {label: 'JSON', value: 'json'},
          {label: '文件', value: 'file'},
        ]}
        fieldProps={{
          onChange: (value) => {
            form.setFieldsValue({settingValue: ''});
            setFileList([]);
          }
        }}
      />
      <ProFormSelect
        name="groupId"
        label="分组"
        rules={[{required: true, message: '请选择配置类型'}]}
        request={async () => {
          const {data} = await listSettingGroupAPI({})
          return data.map((item: API.ISettingGroup) => ({
            label: item.name,
            value: item.id
          }))
        }}
      />

      <Form.Item noStyle shouldUpdate>
        {({getFieldValue}) => {
          const settingType = getFieldValue('settingType');

          if (settingType === 'file') {
            return (
              <Form.Item
                name="settingValue"
                label="配置值"
                rules={[{required: true, message: '请上传文件'}]}
              >
                <Upload
                  fileList={fileList}
                  onChange={handleUploadChange}
                  // beforeUpload={() => false} // 这里替换为实际的上传逻辑
                  maxCount={1}
                  action={'/api/file/upload'}
                >
                  <Button icon={<UploadOutlined/>}>选择文件</Button>
                </Upload>
              </Form.Item>
            );
          }

          if (settingType === 'boolean') {
            return (
              <ProFormSelect
                name="settingValue"
                label="配置值"
                rules={[{required: true, message: '请选择配置值'}]}
                options={[
                  {label: '是', value: 'true'},
                  {label: '否', value: 'false'},
                ]}
              />
            );
          }

          if (settingType === 'number') {
            return (
              <ProFormText
                name="settingValue"
                label="配置值"
                rules={[
                  {required: true, message: '请输入配置值'},
                  {pattern: /^-?\d+\.?\d*$/, message: '请输入有效的数字'}
                ]}
              />
            );
          }

          if (settingType === 'json') {
            return (
              <ProFormTextArea
                name="settingValue"
                label="配置值(JSON)"
                rules={[
                  {required: true, message: '请输入JSON配置'},
                  {
                    validator: (_: any, value: any) => {
                      try {
                        JSON.parse(value);
                        return Promise.resolve();
                      } catch (e) {
                        return Promise.reject('请输入有效的JSON格式');
                      }
                    }
                  }
                ]}
                fieldProps={{
                  rows: 4,
                }}
              />
            );
          }

          // 默认字符串类型
          return (
            <ProFormText
              name="settingValue"
              label="配置值"
              rules={[{required: true, message: '请输入配置值'}]}
            />
          );
        }}
      </Form.Item>

      <ProFormTextArea
        name="description"
        label="配置说明"
        width="lg"
        fieldProps={{
          rows: 3,
        }}
        placeholder="请输入配置项的详细说明"
      />
    </ModalForm>
  );
};

export default SettingForm;
